﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FunasrSTT.Common.Helpers;

/// <summary>
/// 音频文件处理
/// </summary>
public static class WavParser
{
    public static WavInfo ReadWavInfo(byte[] bytes)
    {
        // 基础校验
        if (bytes == null || bytes.Length < 44) return null;

        // 检查RIFF和WAVEfmt标记
        if (!CheckHeaderSegment(bytes, 0, "RIFF") ||
            !CheckHeaderSegment(bytes, 8, "WAVEfmt ")) return null;

        // 解析格式信息
        int formatTag = BitConverter.ToUInt16(bytes, 20);
        int numChannels = BitConverter.ToUInt16(bytes, 22);
        int sampleRate = BitConverter.ToInt32(bytes, 24);
        int bitRate = BitConverter.ToUInt16(bytes, 34);

        // 校验PCM格式和声道数
        if (formatTag != 1 || (numChannels != 1 && numChannels != 2)) return null;

        // 构建头信息
        var headers = new System.Collections.Generic.List<byte[]>();
        headers.Add(SubArray(bytes, 0, 12)); // 基础头
        int headSize = 12;

        // 查找data块
        int dataPos = 0;
        for (int i = 12; i < bytes.Length - 8;)
        {
            if (CheckDataHeader(bytes, i))
            {
                var dataHeader = SubArray(bytes, i, 8);
                headers.Add(dataHeader);
                headSize += 8;
                dataPos = i + 8;
                break;
            }

            int chunkSize = BitConverter.ToInt32(bytes, i + 4);
            if (i == 12) // fmt块
            {
                int fmtSize = 4 + 4 + chunkSize;
                headers.Add(SubArray(bytes, i, fmtSize));
                headSize += fmtSize;
            }
            i += 4;
            i += 4 + chunkSize; // 移动到下一个块
        }

        if (dataPos == 0) return null;

        // 合并头信息
        byte[] wavHead = new byte[headSize];
        int offset = 0;
        foreach (var header in headers)
        {
            Buffer.BlockCopy(header, 0, wavHead, offset, header.Length);
            offset += header.Length;
        }

        return new WavInfo
        {
            SampleRate = sampleRate,
            BitRate = bitRate,
            NumChannels = numChannels,
            WavHead44 = wavHead,
            DataPos = dataPos
        };
    }

    // 检查指定位置的字节是否匹配ASCII字符串
    private static bool CheckHeaderSegment(byte[] bytes, int offset, string expected)
    {
        if (bytes.Length < offset + expected.Length) return false;
        for (int i = 0; i < expected.Length; i++)
        {
            if (bytes[offset + i] != (byte)expected[i]) return false;
        }
        return true;
    }

    // 检查是否是"data"块
    private static bool CheckDataHeader(byte[] bytes, int offset)
    {
        return bytes[offset] == 'd' &&
               bytes[offset + 1] == 'a' &&
               bytes[offset + 2] == 't' &&
               bytes[offset + 3] == 'a';
    }

    // 安全的数组切片
    private static byte[] SubArray(byte[] source, int offset, int length)
    {
        byte[] result = new byte[length];
        Buffer.BlockCopy(source, offset, result, 0, length);
        return result;
    }
}

/// <summary>
/// 音频文件信息
/// </summary>
public class WavInfo
{
    public int SampleRate { get; set; }
    public int BitRate { get; set; }
    public int NumChannels { get; set; }
    public byte[] WavHead44 { get; set; }
    public int DataPos { get; set; }
}

